<route lang="json5">
{
  style: {
    navigationBarTitleText: '借书',
    navigationStyle: 'custom',
    // #ifdef MP-ALIPAY
    enablePullDownRefresh: false,
    'mp-alipay': {
      allowsBounceVertical: 'NO',
      transparentTitle: 'always',
      titlePenetrate: 'YES',
      defaultTitle: '',
    },
    // #endif
  },
}
</route>

<template>
  <view class="navbar" :style="{ paddingTop: safeAreaInsets.top + 'px' }">
    <view class="search-box">
      <image src="../../static/search/left.png" mode="" @tap="back"></image>
      <view class="input-box">
        <uni-icons class="icon" type="search" size="20" @tap="search" />
        <!-- <uni-search-bar v-model="searchValue"></uni-search-bar> -->
        <input
          v-model="searchValue"
          type="text"
          :placeholder="placeholderValue"
          placeholder-class="placeholder"
          @confirm="search"
          @focus="focus"
          @blur="isShowSearch = false"
        />
        <view v-if="isShowClear" class="uni-searchbar__box-icon-clear" @click="clear">
          <slot name="clearIcon">
            <uni-icons color="#c0c4cc" size="20" type="clear" />
          </slot>
        </view>
        <!-- <image src="../../static/search/scan.png" mode=""></image> -->
      </view>
    </view>
  </view>
  <view class="content" v-if="isShowSearch">
    <view class="title">
      <text>历史搜索</text>
      <view class="clear-box" @tap="clearHistoryList">
        <image src="../../static/global/del.png" mode=""></image>
        <text>清空</text>
      </view>
    </view>
    <view class="child">
      <view
        class="item"
        v-for="(item, index) in searchRef.historyList"
        :key="index"
        @tap="clickSearchItem(item)"
      >
        <text>{{ item }}</text>
      </view>
    </view>
  </view>

  <view class="content" v-if="isShowSearch">
    <view class="title">
      <text>热搜达人</text>
    </view>
    <view class="child">
      <view
        class="item"
        :class="item.type == 2 ? 'item-a' : ''"
        v-for="(item, index) in userTopList"
        :key="index"
        @tap="clickSearchItem(item.name)"
      >
        <image v-if="item.image" :src="item.image" mode=""></image>
        <text>{{ item.name }}</text>
      </view>
    </view>
  </view>

  <view class="content" v-if="isShowSearch">
    <view class="title">
      <text>热搜书籍 TOP</text>
    </view>
    <view class="list">
      <view
        class="item"
        v-for="(item, index) in bookTopList"
        :key="index"
        @tap="clickBookTopItem(item.id)"
      >
        <view class="cover-box">
          <view class="label" :class="'label-' + index">
            <text>{{ index + 1 }}</text>
          </view>
          <image :src="item.image" mode=""></image>
        </view>
        <view class="item-info-box">
          <text>{{ item.name }}</text>
          <view>
            <image
              :src="index > 2 ? '../../static/search/huo_.png' : '../../static/search/huo.png'"
              mode=""
            ></image>
            <text :style="index > 2 ? 'color:#B1B1B1' : ''">{{ index + 1 }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>

  <view v-if="!isShowSearch">
    <scroll-view
      :scroll-top="scrollTop"
      :scroll-y="true"
      class="scroll-Y"
      refresher-enabled
      :refresher-triggered="isTriggered"
      @refresherrefresh="upper"
      @scrolltolower="lower"
    >
      <uni-group
        title="用户"
        mode="card"
        v-if="
          searchUserResList && searchUserResList.length != 0 && props.type != SearchTypeEnum.ORDER
        "
      >
        <uni-list :border="true">
          <uni-list-chat
            v-for="user in searchUserResList"
            :key="user.id"
            :avatar-circle="true"
            :title="user.name"
            :avatar="user.image"
            :note="user.description"
          >
            <view class="chat-custom-right">
              <!-- <view class="status">{{ user.statusStr }}</view> -->
              <button
                class="mini-btn optBtn"
                hover-class="button-active"
                size="mini"
                @tap="clickUser(user)"
              >
                详情
              </button>
            </view>
          </uni-list-chat>
        </uni-list>
      </uni-group>
      <uni-group
        title="书籍"
        mode="card"
        v-if="
          searchBookResList && searchBookResList.length != 0 && props.type != SearchTypeEnum.ORDER
        "
      >
        <uni-list :border="true">
          <uni-list-chat
            v-for="book in searchBookResList"
            :key="book.id"
            :title="book.name"
            :avatar="book.image"
            :note="'作者: ' + book.author"
          >
            <view class="chat-custom-right">
              <!-- <view class="status">{{ book.statusStr }}</view> -->
              <button
                class="mini-btn optBtn"
                hover-class="button-active"
                size="mini"
                @tap="clickBook(book)"
              >
                详情
              </button>
            </view>
          </uni-list-chat>
        </uni-list>
      </uni-group>
      <!-- <uni-group
        title="小组"
        mode="card"
        v-if="searchGroupResList && searchGroupResList.length != 0"
      >
        <uni-list :border="true">
          <uni-list-chat
            v-for="group in searchGroupResList"
            :key="group.id"
            :title="group.name"
            :avatar="group.image"
            :note="group.description"
          >
            <view class="chat-custom-right">
              <view class="status">{{ group.statusStr }}</view>
              <button
                class="mini-btn optBtn"
                hover-class="button-active"
                size="mini"
                @tap="clickGroup(group)"
              >
                详情
              </button>
            </view>
          </uni-list-chat>
        </uni-list>
      </uni-group> -->
      <view
        v-if="
          props.type == SearchTypeEnum.ORDER && searchOrderResList && searchOrderResList.length != 0
        "
        style="
          background-color: #eeeeee;
          height: 60rpx;
          line-height: 60rpx;
          color: #666666;
          font-size: 34rpx;
          padding: 10px 15px;
          margin: 0px 13px;
          border-top-left-radius: 10rpx;
          border-top-right-radius: 10rpx;
        "
      >
        订单
      </view>
      <uni-card
        v-if="
          props.type == SearchTypeEnum.ORDER && searchOrderResList && searchOrderResList.length != 0
        "
        :title="'《' + recordItem.bookName + '》'"
        :sub-title="'作者: ' + recordItem.bookAuthor"
        :extra="recordItem.statusStr"
        :thumbnail="recordItem.bookAvatar"
        v-for="(recordItem, index) in searchOrderResList"
        :key="recordItem.id"
      >
        <view class="options">
          <text>订单号: {{ ''+recordItem.orderId+'</text>' }}</text>
          <text>借阅人: {{ recordItem.borrowUserName }}</text>
          <text>到期时间: {{ recordItem.deadline }}</text>
          <button
            v-if="recordItem.status === OrderStatus.BORROWING"
            class="mini-btn .button1"
            hover-class="button-active"
            size="mini"
            @tap="updateStatus(recordItem, OrderStatus.APPROVE)"
          >
            同意
          </button>
          <button
            v-if="recordItem.status === OrderStatus.BORROWING"
            class="mini-btn .button2"
            hover-class="button-active"
            size="mini"
            @tap="updateStatus(recordItem, OrderStatus.REJECTED)"
          >
            拒绝
          </button>
          <button
            v-if="recordItem.status === OrderStatus.RETURN"
            class="mini-btn .button1"
            hover-class="button-active"
            size="mini"
            @tap="updateStatus(recordItem, OrderStatus.DONE)"
          >
            确认归还
          </button>
        </view>
        <view class="remarks">
          <image
            v-if="recordItem.status != 0"
            style="width: 60rpx; height: 60rpx; border-radius: 50%"
            :src="recordItem.borrowUserAvatar"
            mode="scaleToFill"
          />
          <text v-if="recordItem.status != 0" class="uni-body">
            &nbsp;: {{ recordItem.remark }}
          </text>
        </view>
      </uni-card>
      
    <NullView
      v-if="isNull"
      content="未搜到任何结果"
      href=""
      url=""
    ></NullView>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { searchApi, searchOrderApi, searchCollectionApi, searchTopListApi } from '@/service/global'
import { bookInfoApi } from '@/service/book'
import { SearchTypeEnum } from '@/enums/SearchTypeEnum'
import { useSearchStore } from '@/store/search'
import { Search, SearchItem } from '@/types/search'
import { OrderDirection, OrderStatus } from '@/enums/OrderStatus'
import { Order } from '@/types/order'
import { updateStatusApi } from '@/service/order'
import NullView from '@/components/NullView.vue'

const searchRef = useSearchStore()
let userTopList = ref<SearchItem[]>([])
let bookTopList = ref<SearchItem[]>([])

let searchUserResList = ref<SearchItem[]>([])
let searchBookResList = ref<SearchItem[]>([])
let searchGroupResList = ref<SearchItem[]>([])
let searchOrderResList = ref<Order[]>([])

let safeAreaInsets = uni.getSystemInfoSync().safeAreaInsets
let searchValue = ref<string>('')
let isShowSearch = ref<boolean>(true)
let isShowClear = ref<boolean>(false)
isShowClear = computed(() => searchValue.value != undefined)

let scrollTop = ref(0)

let isNull = computed(()=> {
  return (!searchOrderResList.value || searchOrderResList.value.length == 0)
  && (!searchUserResList.value || searchUserResList.value.length == 0)
  && (!searchBookResList.value || searchBookResList.value.length == 0)
})


const props = defineProps<{
  type: number
  direction: number
}>()
let placeholderValue = computed(() => {
  if (!props.type) {
    return '搜索'
  } else if (SearchTypeEnum.USER == props.type) {
    return '搜索用户'
  } else if (SearchTypeEnum.BOOK == props.type) {
    return '搜索书籍'
  } else if (SearchTypeEnum.GROUP == props.type) {
    return '搜索小组'
  }
})

onLoad(async () => {
  const userToptRes = await searchTopListApi(SearchTypeEnum.USER)
  userTopList.value = userToptRes.data
  const bookTopRes = await searchTopListApi(SearchTypeEnum.BOOK)
  bookTopList.value = bookTopRes.data
})

const back = () => {
  uni.navigateBack()
}
const search = async () => {
  if (SearchTypeEnum.ORDER == props.type) {
    const searchOrderRes = await searchOrderApi(props.direction, searchValue.value)
    console.log('searchOrderRes', searchOrderRes)
    searchOrderResList.value = searchOrderRes.data
    isShowSearch.value = false
  } else {
    if(!searchValue.value || searchValue.value.trim() == '') return
    searchRef.searchHistory(searchValue.value)
    const res = await searchApi(props.type, searchValue.value)
    console.log('searchRes', res)
    searchUserResList.value = res.data.userList
    searchBookResList.value = res.data.bookList
    searchGroupResList.value = res.data.groupList
    isShowSearch.value = false
  }
}
const focus = () => {
  isShowSearch.value = true
}
const clear = () => {
  searchValue.value = ''
  isShowSearch.value = true
}
const clearHistoryList = () => {
  searchRef.clearSearch()
  isShowSearch.value = true
}
const clickSearchItem = (item) => {
  searchValue.value = item
  search()
}

const clickUser = (user: SearchItem) => {
  // 用户
  searchCollectionApi(SearchTypeEnum.USER, user.id)
  uni.navigateTo({ url: '/pages/search/userInfo?id=' + user.id })
}
const clickBook = (book: SearchItem) => {
  // 书籍
  searchCollectionApi(SearchTypeEnum.BOOK, book.id)
  uni.navigateTo({ url: '/pages/search/bookInfo?id=' + book.id })
}
const clickGroup = (group: SearchItem) => {
  // 小组
  searchCollectionApi(SearchTypeEnum.GROUP, group.id)
  uni.navigateTo({ url: '/pages/search/groupInfo?id=' + group.id })
}

const clickBookTopItem = (bookId: number) => {
  // book id
  searchCollectionApi(SearchTypeEnum.BOOK, bookId)
  uni.navigateTo({ url: '/pages/search/bookInfo?id=' + bookId })
}

const updateStatus = async (order: Order, status: number) => {
  uni.showLoading({ title: '请稍后...' })
  const updateStatusRes = await updateStatusApi({ id: order.id, status: status })
  console.log('updateStatus res', updateStatusRes)
  order.status = updateStatusRes.data.status
  order.statusStr = updateStatusRes.data.statusStr
  uni.hideLoading()
  uni.showToast({
    title: '已提交',
    mask: true,
  })
}

// 触发下拉刷新
const upper = async () => {
  console.log('下拉刷新')
  isTriggered.value = true
  // 加载数据 api 要加 await
  // ...
  // await Promise.all([guessRef.value?.resetData()])
  setInterval(() => {
    isTriggered.value = false
  }, 1000)
}
const isTriggered = ref(false)

const lower = () => {
  console.log('lower')
}
</script>

<style lang="scss">
page {
  background: #f6f6f6;
}

.top-box {
  height: 44px;
}
.navbar {
  background-image: url(@/static/home/navigator_bg.png);
  background-size: cover;
}
.search-box {
  display: flex;
  /*  #ifndef MP-WEIXIN  */
  justify-content: space-between;
  /* #endif */
  align-items: center;
  margin: 0 24rpx;
  height: 44px;

  image {
    width: 50rpx;
    height: 50rpx;
    flex-shrink: 0;
  }

  text {
    flex-shrink: 0;
    color: #dbdbdb;
  }
}

.input-box {
  display: flex;
  align-items: center;

  background-color: rgba(255, 255, 255, 0.5);
  height: 72rpx;
  border-radius: 72rpx;
  padding: 0 30rpx;
  width: 50%;
  margin: 0 24rpx;

  .icon {
    opacity: 0.5;
  }
  input {
    font-size: 30rpx;
    width: 100%;
  }
  .placeholder {
    color: rgb(130, 130, 130);
  }
  image {
    width: 48rpx;
    height: 48rpx;
  }
}

.content {
  margin: 24rpx;
}

.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 24rpx 0;

  text {
    font-size: 30rpx;
    font-weight: bold;
  }
}

.clear-box {
  color: #868686;
  font-size: 28rpx;
  display: flex;
  align-items: center;

  image {
    width: 32rpx;
    height: 32rpx;
    margin-right: 2rpx;
  }
}

.child {
  display: flex;
  flex-wrap: wrap;

  .item {
    background: #fff;
    font-size: 28rpx;
    height: 62rpx;
    border-radius: 54rpx;
    padding: 0 28rpx;
    color: #525252;
    margin: 0 24rpx 20rpx 0;
    display: flex;
    align-items: center;
    image {
      width: 40rpx;
      height: 40rpx;
      border-radius: 40rpx;
      margin-right: 10rpx;
    }
  }

  .item-a {
    padding: 0 28rpx 0 14rpx;
  }
}

.list {
  background: #fff;
  border-radius: 24rpx;
  padding: 15rpx 30rpx;

  .item {
    display: flex;
    padding: 15rpx 0;
  }
}

.item-info-box {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  color: #333333;

  text {
    -webkit-text-stroke-width: 0.1px;
    font-size: 30rpx;
  }

  view {
    color: #ff4466;
    -webkit-text-stroke-width: 0.3px;
    font-size: 28rpx;
    display: flex;
    align-items: center;

    image {
      width: 30rpx;
      height: 30rpx;
      margin-right: 4rpx;
    }
  }
}

.cover-box {
  position: relative;
}

.cover-box .label {
  position: absolute;
  top: 0;
  left: 0;
  width: 44rpx;
  height: 44rpx;
  z-index: 1;
  border-top-left-radius: 14rpx;
  border-bottom-right-radius: 14rpx;
  text-align: center;
  line-height: 44rpx;
  color: #fff;
  font-size: 28rpx;
  -webkit-text-stroke-width: 0.1px;
}

.label-0 {
  background: #e05345;
}

.label-1 {
  background: #eb9941;
}

.label-2 {
  background: #edc744;
}

.label-3 {
  background: #696765;
}

.cover-box image {
  width: 120rpx;
  height: 120rpx;
  flex-shrink: 0;
  border-radius: 14rpx;
  margin-right: 30rpx;
}

.uni-searchbar__box-icon-clear {
  align-items: center;
  line-height: 24px;
  padding-left: 8px;
  /* #ifdef H5 */
  cursor: pointer;
  /* #endif */
}

.optBtn {
  width: 150rpx;
  position: absolute;
  right: 0rpx;
  top: 30%;
  color: #fff;
  font-size: 25rpx;
  background-color: $main-color-hight;
}
.button-active {
  background-color: $main-color; /* 点击时的背景颜色 */
}
.status {
  position: absolute;
  right: 0rpx;
  font-size: 32rpx;
  color: #b3b3b3;
}

.options {
  width: 100%;
  margin-bottom: 10rpx;

  text {
    display: block;
    font-size: 28rpx;
    color: $main-color-hight;
  }

  .button1 {
    float: right;
    color: #fff;
    font-size: 30rpx;
    background-color: $main-color-hight;
    margin-left: 20rpx;
  }
  .button2 {
    float: right;
    color: #fff;
    font-size: 30rpx;
    background-color: $main-color-hight;
  }

  .button-active {
    background-color: $main-color; /* 点击时的背景颜色 */
  }
}
.remarks {
  margin-left: 5%;
  width: 70%;
}
</style>
